package com.rmfyzxfw.caseprocess.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.rmfyzxfw.caseprocess.boot.result.ApiResult;
import com.rmfyzxfw.caseprocess.boot.result.CommonStatusCode;
import com.rmfyzxfw.caseprocess.boot.result.R;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @description: RestTemplate文件下载登录过期统一处理
 * @Author: GYW  742926306@qq.com
 * @Date: 2023/5/10 11:34
 */
public class HttpFileDownloadHandlerUtil {
    /**
     * 文件流统一异常处理
     *
     * @param resource
     * @return
     */
    public static ApiResult<Resource> getInputStreamResult(Resource resource) {
        /*没有签名时返回null*/
        if(Objects.isNull(resource)){
            return R.success();
        }
        if (StringUtils.isNotBlank(resource.getFilename())) {
            return R.success(resource);
        }
        try {
            byte[] bytes = IOUtils.toByteArray(resource.getInputStream());
            JSONObject jsonObject = JSON.parseObject(new String(bytes, StandardCharsets.UTF_8));
            if (Objects.equals(jsonObject.getInteger("status"), 401)) {
                return R.fail(CommonStatusCode.JURY_UNAUTHORIZED);
            }

            throw new RuntimeException("服务器错误：" + jsonObject.getString("message"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 字节流流统一异常处理
     *
     * @param bytes
     * @return
     */
    public static ApiResult<byte[]> getByteArrayResult(byte[] bytes) {
        try {
            JSONObject jsonObject = JSON.parseObject(new String(bytes, StandardCharsets.UTF_8));
            if (Objects.equals(jsonObject.getInteger("status"), 401)) {
                return R.fail(CommonStatusCode.JURY_UNAUTHORIZED);
            }

            throw new RuntimeException("服务器错误：" + jsonObject.getString("message"));
        } catch (JSONException e) {
            return R.success(bytes);
        }
    }
}